package com.meida.module.bus.provider.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.springmvc.base.BaseController;
import com.meida.module.bus.client.entity.BusProjectFile;
import com.meida.module.bus.provider.service.BusProjectFileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Description: 上传文件
 * @Author: ccc
 **/
@Controller
@ResponseBody
@RequestMapping("/up/file")
public class BusProjectFileController extends BaseController<BusProjectFileService, BusProjectFile> {

	@Autowired
	private BusProjectFileService upFileService;

	@Value("${file.url}")
	public String filePath;

    public static SimpleDateFormat ymdhmsdfStr = new SimpleDateFormat("yyyyMMddHHmmss");

    @ApiOperation(value = "分页列表", notes = "分页列表")
    @GetMapping(value = "/page")
    public ResultBody pageList(@RequestParam(required = false) Map params) {
        //设置查询条件
        CriteriaQuery<BusProjectFile> cq = new CriteriaQuery(BusProjectFile.class);
        if(params.containsKey("purchaseId")) {
            cq.eq("purchaseId", params.get("purchaseId"));
        }
        if(params.containsKey("projectId")) {
            cq.eq("projectId", params.get("projectId"));
        }
        long current = Long.parseLong(params.get("page").toString());
        long limit = Long.parseLong(params.get("limit").toString());
        IPage<BusProjectFile> page = new Page<>(current, limit);
        return ResultBody.ok(bizService.page(page, cq));
    }

    /**
     * 上传多个附件
     * @param request
     * @param files
     * @return
     * @throws Exception
     */
    @PostMapping("/upFiles")
    public ResultBody upFiles(HttpServletRequest request, @RequestParam("file") MultipartFile[] files,
                              @RequestParam(required = false) Long projectId,
                              @RequestParam(required = false) String uniqueFlag) throws Exception {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        String fileName = files[0].getOriginalFilename();
        String path = filePath;
        String date = "/" + ymdhmsdfStr.format(new Date()) + (int) (1 + Math.random() * (100 - 1 + 1));
        String nameTypePath = date + "/";
        nameTypePath = nameTypePath.replace(",", "");
        return bizService.upFileService(path + nameTypePath, nameTypePath, files, projectId, uniqueFlag);
    }


	private void setOrigin(HttpServletResponse response) {
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "*");
		response.addHeader("Access-Control-Allow-Headers",
				"Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,X-E7M-With");
	}

	@GetMapping("/download")
	public void download(@RequestParam String projectFileId, HttpServletResponse response) {
        BusProjectFile projectFile = upFileService.getById(projectFileId);
		setOrigin(response);
		String downFilePath = filePath + projectFile.getFilePath();
		File file = new File(downFilePath);
		response.setContentLength((int) file.length());
		try (FileInputStream fis = new FileInputStream(file); OutputStream os = response.getOutputStream()) {
			byte[] buf = new byte[1024 * 256];
			int i;
			while ((i = fis.read(buf)) != -1) {
				os.write(buf, 0, i);
			}
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    @PostMapping("/download/base64")
    public ResultBody downloadBase64(@RequestParam String projectFileId) {
        BusProjectFile projectFile = upFileService.getById(projectFileId);
        String downFilePath = filePath + projectFile.getFilePath();
        File file = new File(downFilePath);
        String base64String = null;
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream byteos = new ByteArrayOutputStream();
            int read;
            int length = is.available();
            byte[] bytes = new byte[length];
            while ((read = is.read(bytes)) > 0) {
                byteos.write(bytes, 0, read);
            }
            base64String = Base64Utils.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.failed(e.getMessage());
        }
        return ResultBody.ok(base64String);
    }

}
